<?php
/**
 * @class MisPlugin
 * @desc 运行每个action 要做的hook,主要包括，判断用户登录情况,记录用户日志等...
 *
 * @author mt
 */
header('content-type:text/html;charset=utf-8');

class MisPlugin extends Yaf_Plugin_Abstract
{
    public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {

        $cookieConfig = Yaf_Registry::get("config")->cookie;
        //设置用户id
        $uip = $this->getUserIp();
        $uid = $request->getCookie($cookieConfig['uid']);
        if(empty($uid)){
            $uid = md5($uip.time());
            setcookie($cookieConfig['uid'], $uid, time()+60*60*24*365, '/', $cookieConfig['domain']);
        }

        $request->setParam('uid',$uid);
        $request->setParam('uip',$uip);
    }

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response)
    {
        try {
            //验证用户登录情况
            $session = Yaf_Registry::get('session');
            $uid = $request->getCookie('PUSER');
            $params = $request->getParams();
            $cName = $request->getControllerName();
            $aName = $request->getActionName();
            SmartyAdapter::assign('controllerName', strtolower($cName));
            SmartyAdapter::assign('actionName', strtolower($aName));
            $defaultTtemplateName = strtolower($cName.'/'.$aName);
            //设置模板名

            SmartyAdapter::$templateName = $defaultTtemplateName;
            $arrCacheConfig = Template::$cache;
            SmartyAdapter::assign('sysname', Yaf_Registry::get("config")->sysname);
            SmartyAdapter::assign('tjzxname', Yaf_Registry::get("config")->tjzxname);
            SmartyAdapter::assign('jcname', Yaf_Registry::get("config")->jcname);
            $callline = Yaf_Registry::get("config")->callline;
            SmartyAdapter::assign('callline', $callline ? $callline : 'ykf');

            //录音地址
            SmartyAdapter::assign('soundfileurl', RECORD_FILE);

            //wss地址
            SmartyAdapter::assign('wss_url', WSS_URL);

            //判断是否要缓存
            if (isset($arrCacheConfig[$defaultTtemplateName]) && $tplCache = $arrCacheConfig[$defaultTtemplateName]) {
                //需要缓存
                if ($tplCache['cache']) {
                    //配置缓存
                    $cacheConfig = array(
                        'cache' => true,
                        'lifeTime' => $tplCache['lifeTime'],
                    );
                    //assign key
                    if (isset($tplCache['key'])) {
                        $cacheConfig['key'] = array();
                        foreach ($tplCache['key'] as $key) {
                            if ($params[$key]) {
                                $cacheConfig['key'][] = $params[$key];
                            }
                        }
                    }

                    //设置缓存
                    SmartyAdapter::setCacheConfig($cacheConfig);
                    $isCached = SmartyAdapter::isCached();

                    if ($isCached) {
                        //显示缓存的模板
                        SmartyAdapter::display();
                        //直接退出，不需要请求数据等操作
                        exit();
                    }
                }
            }

            //未登录或者session过期，跳转
            if (!in_array($cName, ['Login', 'Vcode','error'])) {
                if(! (isset($_POST['source_type']) && $_POST['source_type']== "GH")){ //防止上传终端
                    if (empty($uid)) {
                        if($request->isXmlHttpRequest()){
                            AjaxTool::returnJsonData(401);
                        }
                        if(!in_array(strtolower($cName),array('login','vcode','img','favicon.ico')) && !$request->isXmlHttpRequest()) {
                            $url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
                            $url .= $_SERVER['HTTP_HOST'];
                            $url .= isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']);
                            Func_Cachefunc::getInstance()->set($request->getParam('uid'), $url, 86400);
                        }
                        $response->setRedirect('/login');
                        exit;
                    }
                    //验证是否真实用户且session
                    $adminInfo = UserAuth::getAuth();
                    if (empty($adminInfo)) {
                        if($request->isXmlHttpRequest()){
                            AjaxTool::returnJsonData(401);
                        }
                        $response->setRedirect('/login');
                        exit;
                    }

                    $mobile = hexdec($adminInfo[0]);
                    $time = hexdec($adminInfo[1]);
                    $admin = Module_User_Administrator::getInstance()->getByMobile($mobile);
                    if (!$admin) {
                        if($request->isXmlHttpRequest()){
                            AjaxTool::returnJsonData(401);
                        }
                        $response->setRedirect('/login');
                        exit;
                    }
                    $this->maskName($admin['name']);
                    if($admin['mediationOrganId'] == 4){
                        SmartyAdapter::assign('mediationNum', '其金调');
                    }else{
//                        SmartyAdapter::assign('mediationNum', Yaf_Registry::get("config")->mediationNum);
                        SmartyAdapter::assign('mediationNum', '云金调');
                    }
                    //查询呼叫中心通道 1联通 2自有呼叫中心
                    Yaf_Registry::set('power_role_id', $admin['role_id']);
                    //验证用户存在

                    if ($admin['random_key'] !== $_COOKIE['random_key']) {
                        if($request->isXmlHttpRequest() && $_COOKIE['random_key'] ){
                            AjaxTool::returnJsonData(401,"您的账号已在别处登录，如非本人操作请及时修改密码！");
                        }
                        if($request->isXmlHttpRequest() && !$_COOKIE['random_key'] ){
                            AjaxTool::returnJsonData(401);
                        }
                        echo '<script>alert("您的账号已在别处登录，如非本人操作请及时修改密码！");window.location.href="/login";</script>';
                        die;
                    }
                    if ($admin['status'] == 3) {
                        if($request->isXmlHttpRequest()){
                            AjaxTool::returnJsonData(401,"您的账号没有权限，将退出本系统");
                        }
                        echo '<script>alert("您的账号没有权限，将退出本系统");window.location.href="/login";</script>';
                        die;
                    }
                    $role = Module_User_Role::getInstance()->getRoleById($admin['role_id']);
                    $admin['role_title'] = $role ? $role['title'] : '';
                    $now = time();
                    //过期时间半小时
                    if ($now - $time > 120 * 60) {
                        if($request->isXmlHttpRequest()){
                            AjaxTool::returnJsonData(401);
                        }
                        $response->setRedirect('/login');
                    } else {
                        if($admin['workerId'] && $admin['workerId2']){
                            $select_wokerId = Lib_Redis_String::get($admin['id']);
                            $workerId = $select_wokerId ? $select_wokerId : ($admin['workerId'] ? $admin['workerId'] : $admin['workerId2'] );
                        }else{
                            $workerId = $admin['workerId'] ? $admin['workerId'] : $admin['workerId2'];
                        }
                        UserAuth::setAuth($mobile);
                        SmartyAdapter::assign('admin', $admin);
                        SmartyAdapter::assign('workerId', $workerId);
                        Yaf_Registry::set('curUser', $admin);
                        //检查用户权限
                        $hasProv = $this->checkUserProvisioning($admin, $request);
                        // 无权限
                        if (empty($hasProv)) {
                            if($request->isXmlHttpRequest()){
                                AjaxTool::returnJsonData(403);
                            }
                            SmartyAdapter::$templateName = 'error/auth';
                            SmartyAdapter::display();
                            exit();
                        }
                    }
                }
            }
        }catch (Exception $e){
            SmartyAdapter::$templateName = 'error/server';
            SmartyAdapter::display();
            exit();
        }


    }

    public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response)
    {
        //显示模板
        SmartyAdapter::display();
    }

    //检查用户权限
    public function checkUserProvisioning($admin, $request)
    {
        $cName = strtolower($request->getControllerName());
        $aName = strtolower($request->getActionName());
        $roleId = intval($admin['role_id']);
        $list = Module_User_Provisioning::getInstance()->getListByRoleId($roleId);
        $list = array_column($list,null,'id');
        $iconList=  Module_User_Provisioning::getInstance()->getAllBySearch([],["where"=>["parent_id=0"]]);
        $iconList= array_column($iconList,null,'id');


        $update_expire_time = 0;
        $controllers = array();
        //不用验证的控制器
        $userProvi = [
            'user-editpassword'=>1,
            'index-index'=>1,
            'workernumber-downTemplate'=>1,
        ];
        foreach ($list as $_info) {
            if($_info['parent_id']!=0){
               $tmp_seq_key =  $iconList[$_info['parent_id']]['seq'];
                $c_name =  $iconList[$_info['parent_id']]['name'];
                $userMenu[$tmp_seq_key]['data'][] = $_info;
                $userMenu[$tmp_seq_key]['c_name'] = $c_name;
                $userMenu[$tmp_seq_key]['name'][] = $_info['name'];
                $userMenu[$tmp_seq_key]['controller'][] = $_info['controller'];
                $userProvi[strtolower($_info['controller'] . '-' . $_info['action'])] = 1;
                if($_info['c_parent']!==0){
                    $userMenu[$tmp_seq_key]['icon'] = $iconList[$_info['parent_id']]['icon'];
                }
                if($cName == $_info['controller'] && $aName == $_info['action']){
                    SmartyAdapter::assign('parent_name', $_info['c_parent']);

                }
           }

        }
        //已经菜单排序
        krsort($userMenu);
        //二级菜单排序
        foreach ($userMenu as $k1=>$v1){
            array_multisort(array_column($v1['data'],'seq'),SORT_DESC,$userMenu[$k1]['data']);
        }
        SmartyAdapter::assign('userMenu', ($userMenu));
        SmartyAdapter::assign('update_expire_time', $update_expire_time);
        SmartyAdapter::assign('roleList', $controllers);
        SmartyAdapter::assign('roleId', $roleId);
        if($aName == 'selectworkerid'){
            return true;
        }
        //非超级管理员及首页，触发权限管理
        if ($roleId > 1) {
           return isset($userProvi[$cName . '-' . $aName]) ? true : false;
        }
        return true;
    }
    public function getUserIp(){

        $realip = '0.0.0.0';

        if (isset($_SERVER)){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach ($arr AS $ip){
                    $ip = trim($ip);

                    if ($ip != 'unknown'){
                        $realip = $ip;

                        break;
                    }
                }
            }
            elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }
            else{
                if (isset($_SERVER['REMOTE_ADDR'])){
                    $realip = $_SERVER['REMOTE_ADDR'];
                }
                else{
                    $realip = '0.0.0.0';
                }
            }
        }
        else{
            if (getenv('HTTP_X_FORWARDED_FOR')){
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            }
            elseif (getenv('HTTP_CLIENT_IP')){
                $realip = getenv('HTTP_CLIENT_IP');
            }
            else{
                $realip = getenv('REMOTE_ADDR');
            }
        }

        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

        return $realip;
    }

    private function maskName($name)
    {
        if (preg_match("/[\x7f-\xff]/", $name)) {
            $sys_name = mb_substr($name,-2,2,"utf-8");
        } else {
            if(strlen($name) < 6){
                $sys_name = $name;
            }else{
                $sys_name = substr( $name, 0, 1 );
            }
        }
        SmartyAdapter::assign('sys_name', $sys_name);

    }

}
